;
cmedit.TargetSystem = (function($, window, document) {
	var thisContext;
	var index=0;
    var startPage=1;
    var userColumnIds=[];
    var loadTimeout = cmedit.global.loadTimeout;
    var tenantId = window.localStorage.getItem("tenantId");
	var userId = window.sessionStorage.getItem("userId");
	var token = window.sessionStorage.getItem("token");
	var distributeFlag = window.sessionStorage.getItem("distributeFlag");
    var topUtil;  //顶层工具类
    var orderName='';
    var pageNow;
    var orderDirection='';
	var TargetSystemClass = function(){
    	
    }
    TargetSystemClass.prototype =  {
    	constructor : TargetSystemClass,
    	
        init : function() {
        	thisContext = this;
        	topUtil = window.parent.cmedit.global;
        	thisContext.initViewStyle();
        	thisContext.initData();
//        	thisContext.initPage();
        	thisContext.initEvent();
        	thisContext.initTargetList();
        },
        refresh : function(){
        	$('#manusendTable').bootstrapTable('refresh');
        },
        /**
         * 初始化页面视图
         */
        initViewStyle : function() {
            $('.re_contleft .slimScrollDiv').css('height',$(document).height()-116+'px');
            $('.tab-content').css('height',$('.portlet-body').innerHeight()+'px');
            /*$('.line-body').css('height',$('.cont_container').innerHeight()-203+'px');

            修改滚动条样式
            var linescroll_height=$('.line-body').height();
            thisContext.scrollType('line-body',linescroll_height);*/
            
            $('#startTime').datepicker({clearBtn: true,format: 'yyyy-mm-dd',autoclose: true});
            $('#endTime').datepicker({clearBtn: true,format: 'yyyy-mm-dd',autoclose: true});
        },
        /**
         * 时间排序
         */
        orderby : function(id,orderDirectionName){
        	orderName=id;
        	orderDirection=orderDirectionName;
        	 thisContext.initData(pageNow);
        },
        /**
         * 初始化数据
         */
        initData : function(_currentPage,_pageSize) {
        	window.parent.cmedit.ManuscriptSystem.updatePortalStorageExpireTime();
//        	$('#manusendBody').html(cmedit.global.loaderHtml);
        	var $tableid = $('#manusendTable');
        	var url = cmedit.global.cmsPath+"NewTargetController/getManuscriptNewTargetByPage";
        	var gc = JSON.parse(window.sessionStorage.getItem(cmedit.global.cmeditSend));
        	var cmeditList = JSON.parse(window.sessionStorage.getItem(cmedit.global.cmeditTypes));
        	var hasCheckbox = true;
        	if($('#searchContent').val()!=null && $('#searchContent').val()!=''){
        		var title=$('#searchContent').val();
        	}else{
        		var title='';
        	}
//          if($('#endTime').val()!=null && $('#endTime').val()!=''){
            if(($('#endTime').val()!=null && $('#endTime').val()!='') || ($('#startTime').val()!=null && $('#startTime').val()!='')){
        		var dateranges=$("#startTime").val()+" - "+$("#endTime").val();
        	}else{
        		var dateranges='';
        	}
        	var currentPage = _currentPage ? _currentPage : 1;
            var pageSize =_pageSize ? _pageSize : 10;
        	var states=$(".container_buttons button[class*='active']").attr("states");
        	var columnId=$("#preReportColumn").val()!=""?$("#preReportColumn").val():"";
        	var manuscriptTargetGuid = $("#preReportColumn").val();
        	var queryParams={
            		mbtStatus:states,
            		mainHeader:title,
            		mainType:0, //稿件类型：CMS稿件
            		excludeMbtStatus:1, //不查询待分发的记录
            		dateranges:dateranges,
            		manuscriptTargetGuid:manuscriptTargetGuid.replace("_CRE",""),
                    currentPage:currentPage,
                    pageSize:pageSize
            	};
        	var tableParams = {
        			$tableid: $tableid,
        			url: url,
	        		gc: gc,
	        		hasCheckbox: hasCheckbox,
	        		tenantId: tenantId,
	        		userId: userId,  
	        		token: token,
	        		cmeditList: cmeditList,
	        		resourceType : "manuSend",
	        		callBackLoadData:function(start,size){
	                	thisContext.initData(start,size);
	                }

            };
            TableInit(tableParams, queryParams);       	
        },
        /**
         * 初始化分页
         */
        initPage : function(totalPage){
        	$("#pagination").whjPaging({
                /*pageSizeOpt: [
                    {'value': 5, 'text': '5/page', 'selected': true},
                    {'value': 10, 'text': '10/page'},
                    {'value': 15, 'text': '15/page'},
                    {'value': 20, 'text': '20/page'}
                ],*/
                totalPage: totalPage,
                showPageNum: 4,
                firstPage: '<i class="iconfont icon-diyiye"></i>',
                previousPage: '<i class="iconfont icon-shangyiye"></i>',
                nextPage: '<i class="iconfont icon-xiayiye"></i>',
                lastPage: '<i class="iconfont icon-weiye"></i>',
                skip: 'skip',
                confirm: 'go',
                refresh: 'refresh',
                totalPageText: 'the total {} pages',
                isShowFL: true,
                isShowPageSizeOpt: false,
                isShowSkip: false,
                isShowRefresh: false,
                isShowTotalPage: false,
                isResetPage: true,
                callBack: function (currPage, pageSize) {
                	pageNow=currPage;
                	thisContext.initData(currPage);
                }
            });
        	/*$('#pagination').whjPaging('setPage',1,totalPage);*/
        },
        /**
         * 初始化事件
         */
        initEvent : function() {
            $('.nav-link').on('click',function () {
                $('.nav-link').removeClass('nav_active');
                $(this).addClass('nav_active');
            });
            $('.container_buttons button').on('click',function () {
                $(this).addClass('active').siblings().removeClass('active');
                thisContext.initData();
            });
            /*//栏目筛选功能
			$('#preReportColumn').change(function(){
				thisContext.initData();
			});*/
			//时间筛选绑定change事件
//			$('#endTime').change(function() {
//				thisContext.initData();
//			});
			//刷新列表
			$('.send_refresh').on('click',function(){
				$("#preReportColumn").val('');
				$('#searchContent').val('');
				$("#preReportColumn").selectpicker('refresh');
				$(".container_buttons button[states='']").addClass('active').siblings().removeClass('active');
				$('.date-picker input').val('').datepicker('clearDates');
				//thisContext.initData();
			});
        },
        /**
         * 详情页
         */
        entersendDetail : function(mainGuid,mainHeader){
        	window.parent.cmedit.ManuscriptSystem.enterDetail(mainGuid,mainHeader);
        },
        /**
         *滚动条样式
         */
        scrollType : function(scrollId,scrollHeight) {
            $('.'+scrollId).slimScroll({
                height: scrollHeight,//可滚动区域高度
                size: '5px',//组件宽度
                color: '#999',//滚动条颜色
                railOpacity: .3,//滚动条透明度
                disableFadeOut: true,//鼠标经过可滚动区域时显示组件，离开时隐藏组件
                wheelStep: 20, //滚轮滚动量
                alwaysVisible: true,//始终显示组件
                borderRadius: '7px' //滚动条圆角
            });
        },
        /**
         * 全选
         */
        allfileSelected : function(){
            if($('#allSelected').prop('checked')){
                $('.select-check').prop('checked',true);
                $('.list_check').addClass('list_checked');
                $('.res-one').addClass('ulChecked');

            }else{
                $('.select-check').prop('checked',false);
                $('.list_check').removeClass('list_checked');
                $('.res-one').removeClass('ulChecked');
            }
        },
        /**
         * 选择框点击事件
         */
        listOneCheckClick : function(obj){
            if(!$(obj).prev().prop('checked')){
                $(obj).addClass('list_checked');
                selectIds.push(id);
                if(listTotalCount >= listPageSize){
                	if($('.list_checked').length >= listPageSize){
                        $('#allSelected').prop('checked',true);
                    }
                }else{
                	if($('#manusendBody .list_checked').length == listTotalCount){
                    	$('#allSelected').prop('checked',true);
                    }
                }
            }else{
                $(obj).removeClass('list_checked');
                selectIds.splice($.inArray(id,selectIds),1);
                $('#allSelected').prop('checked',false);
                $('#allSelected').next().removeClass('list_checked');
            }
        },
        /**
         *  初始化栏目
         */
        initColumn : function(){
        	var postData = {
        		"key" : "0003",
        	}
        	topUtil.ajaxRequest({
				type: "post",
				async: false,
				dataType: "json",
				url: cmedit.global.cmsPath+"UserInfoController/getUserColumnByUserId",
				data : postData,
				success: function(data) {
					if(data.status) {
						for(var i=0;i<data.data.length;i++){
							userColumnIds.push(data.data[i].id);
			 				$("#preReportColumn").append('<option value="'+data.data[i].id+'">'+data.data[i].name+'</option>');
			 			}
						userColumnIds=JSON.stringify(userColumnIds);
			     		$("#preReportColumn").selectpicker('refresh');
					}else{
						$.notify(data.msg);
					}
				}
			});
        },
        
        /**
         * 初始化签发目标列表
         */
        initTargetList : function(){
        	topUtil.ajaxRequest({
				type: "GET",
				async: false,
				dataType: "json",
				url: cmedit.global.cmsPath+"NewTargetController/targetSystem/0",
				success: function(data) {
					if(data.status) {
						var html = '';
						var list = data.data;
						for(var i =0;i < list.length;i++){
							$("#preReportColumn").append('<option value="'+list[i].manuscriptTargetGuid+'">'+list[i].manuscriptTargetName+'</option>');
						}

						$("#preReportColumn").selectpicker('refresh');
					}else{
						$.notify(data.msg);
					}
				}
			});
        },
        
        /**
         * 签发重试
         * @param mntGuid
         * @param mainGuid
         */
        reTargetDistribute : function(mntGuid,mainGuid){
        	var postData = {
        		"mntGuid" : mntGuid,
        		"mainGuid" : mainGuid,
        	}
        	if(distributeFlag == '2'){
        		url = cmedit.global.cmsPath+"CmsNewTargetController/reTargetDistribution";
        	}
			if(distributeFlag == '3'){
			    url = cmedit.global.cmsPath+"CmsNewTargetController/reTargetDistributionToPlatform";   		
			}
        	topUtil.ajaxRequest({
				type: "post",
				async: true,
				dataType: "json",
				url: url,
				data: postData,
				success: function(data){
					if(data.status) {
						thisContext.initData();
						$.notify("签发重试成功");
					}else{
						$.notify(data.msg);
					}
				}
			});
        },
        
        /**
         * 删除签发记录
         * @param mntGuid
         */
        deleteDistribute : function(mntGuid){
        	window.parent.cmedit.ManuscriptSystem.deleteDistribute(mntGuid);
        },
        
        /**
         * 审核弹框
         */
        taskModal : function(mainGuid){
        	var checkData={
        		"mainGuid":	mainGuid
        	}
        	topUtil.ajaxRequest({
				type: "post",
				async: true,
				dataType: "json",
				url: cmedit.global.cmsPath+"ManuscriptMainController/censorStrategyExist",
				data: checkData,
				success: function(data){
					if(data.status) {
						window.parent.manuscriptSystem.taskmodalShow(1);
					}else{
						$.notify(data.msg);
					}
				}
			});
        },
        /**
         * 显示分发失败原因
         * @param reason
         */
        showFailReason: function(obj, reason) {
            var thisObj = $(obj).parent().find('.popoverimg');
            var timer = null,
                popBox = thisObj.next(),
                imgtop = thisObj.offset().top,
                imgLeft = thisObj.position().left;
            var maxTop = $(window).height() - 240,
                theadTop = $('.fixed-table-header').offset().top + 155,
                boxWidth = $(".popover-box").outerWidth(),
                arrowWidth = $(".popover-arrow").outerWidth();
            var boxLeft = imgLeft - boxWidth * 0.85;
            console.log("imgtop:" + imgtop + " maxTop:" + maxTop + " theadTop:" + theadTop);
            thisObj.next().css('left', boxLeft + 'px');
            thisObj.next().find('.popover_content').html(reason);
            if (imgtop > maxTop && imgtop > theadTop) {
                popBox.addClass('popbox-transY');
                popBox.children('div:first-child').removeClass('popover-arrow-up').addClass('popover-arrow-down');

            } else {
                popBox.removeClass('popbox-transY');
                popBox.children('div:first-child').removeClass('popover-arrow-down').addClass('popover-arrow-up');
            }
            $(".popover-box").hide();
            popBox.show();
            thisObj.on("mouseout", function() {
                timer = setTimeout(function() {
                    popBox.hide();
                }, 500);
            });
            thisObj.prev().on("mouseout", function() {
                timer = setTimeout(function() {
                    popBox.hide();
                }, 500);
            });
            $(".popover-box").on("mouseover", function() {
                clearTimeout(timer);
                $(this).show();
            }).on("mouseout", function() {
                $(this).hide();
            });
        },
        /**
         * 显示分发失败原因
         * @param reason
         */
        showFailReason: function(obj, reason) {
            var thisObj = $(obj).parent().find('.popoverimg');
            var timer = null,
                popBox = thisObj.next(),
                imgtop = thisObj.offset().top,
                imgLeft = thisObj.position().left;
            var maxTop = $(window).height() - 240,
                theadTop = $('.fixed-table-header').offset().top + 155,
                boxWidth = $(".popover-box").outerWidth(),
                arrowWidth = $(".popover-arrow").outerWidth();
            var boxLeft = imgLeft - boxWidth * 0.85;
            console.log("imgtop:" + imgtop + " maxTop:" + maxTop + " theadTop:" + theadTop);
            thisObj.next().css('left', boxLeft + 'px');
            thisObj.next().find('.popover_content').html(reason);
            if (imgtop > maxTop && imgtop > theadTop) {
                popBox.addClass('popbox-transY');
                popBox.children('div:first-child').removeClass('popover-arrow-up').addClass('popover-arrow-down');

            } else {
                popBox.removeClass('popbox-transY');
                popBox.children('div:first-child').removeClass('popover-arrow-down').addClass('popover-arrow-up');
            }
            $(".popover-box").hide();
            popBox.show();
            thisObj.on("mouseout", function() {
                timer = setTimeout(function() {
                    popBox.hide();
                }, 500);
            });
            thisObj.prev().on("mouseout", function() {
                timer = setTimeout(function() {
                    popBox.hide();
                }, 500);
            });
            $(".popover-box").on("mouseover", function() {
                clearTimeout(timer);
                $(this).show();
            }).on("mouseout", function() {
                $(this).hide();
            });
        },
    };
    return new TargetSystemClass();
})(jQuery, window, document);

$(cmedit.TargetSystem.init());
